package com.dreamspacex.ligox.controller;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.print.Doc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by Administrator on 2016/6/21 0021.
 */

@Controller
@RequestMapping(value = "bp")
public class BusinessPlanController {


    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public ModelAndView upload(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        Document document = new Document();
        String pdfFile = "C:\\Users\\Administrator\\Desktop\\引力8.pdf";
        document.setFile(pdfFile);

        // 限制页数
        int maxPages =document.getNumberOfPages();
        float rotation = 0;
        float zoom = 1;

        String destFile = "E:/";
        String fileName = "xx";

        for (int i = 0; i < maxPages; i++)
        {
            BufferedImage img = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, rotation, zoom);


            // 设置图片的后缀名
            Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("jpg");

            ImageWriter writer = (ImageWriter) iter.next();


            File outFile = new File(destFile + fileName + i + ".jpg");

            FileOutputStream out = new FileOutputStream(outFile);

            ImageOutputStream outImage = ImageIO.createImageOutputStream(out);

            writer.setOutput(outImage);

            writer.write(new IIOImage(img, null, null));

            out.flush();
            out.close();
            writer.dispose();
            img.flush();
        }

        document.dispose();
        System.gc(); // 通知垃圾回收
        System.out.println("done");

        ModelAndView mav = new ModelAndView();
        String bpFile = "";
        mav.addObject("bp_file", bpFile);
        mav.setViewName("bp/create");
        return mav;
    }
}
